import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';

import {
    Button,
    DatePicker,
    Form,
    Input,
    Modal,
    Radio,
    Tag,
    Select,
    InputNumber,
    message,
    Row,
    Col,
    Tree,
} from 'antd';
import { modalLayoutLg, modalLayoutSm } from '@/config/layout';
import { request, useModel } from 'umi';
import './index.less'
import apilist from '@/pages/sysman/index/apilist';

const SelectComp = (props: any, refs: any) => {
    const { initialState, setInitialState } = useModel('@@initialState');
    const { currentUser } = initialState;
    const [code, setCode] = useState('');
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [treeData, settreedata] = useState([]);
    const [value, setvalue] = useState('')
    const [searchStr, setsearchStr] = useState('')
    const [selectObj, setselectObj] = useState({})
    //显示弹窗
    const showModal = () => {
        setIsModalVisible(true);
    };

    //取消
    const handleCancel = () => {
        setIsModalVisible(false);
        setCode('');
        setsearchStr('')
        props.callback && props.callback();
    };
    //确定
    const handleOk = () => {
        if (value == '') {
            message.error('必须选择一个')
        } else {
            console.log(value)
            console.log(code)
            console.log(currentUser.user_name)
            request(`/data/dynamic/query`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                data: {
                    apiID: 'GZW_ORG_03',
                    apiParam: {
                        hyp_org_no: selectObj.id,
                        hyp_org_name: selectObj.name,
                        sno: 1,
                        updater: currentUser.user_name,
                        rls_id: code,
                    }

                }
            }).then((res) => {
                console.log(res)
                message.success(res?.meta?.msg);
                handleCancel();
            })
        }
    };
    useImperativeHandle(refs, () => ({
        init: (id: any, record: any) => {
            setCode(id);

            showModal();
            // setfileList([]);
        },
    }));
    const handleHblOrgTreeList = (list) => {
        console.log(list);
        // 首先按照sno字段对菜单数组进行排序
        list.sort((a, b) => a.id - b.id);
        // 构建一个以suporg为键的映射，映射值为菜单项的数组
        const orgMap = list.reduce((acc, org) => {
            if (!acc[org.parentid]) {
                acc[org.parentid] = [];
            }
            acc[org.parentid].push(org);
            return acc;
        }, {});
        // 定义递归函数来构建树形结构
        function buildTree(list, parentKey = '') {
            return list
                .filter((org) => org.parentid === parentKey)
                .map((org) => {
                    let children = buildTree(list, org.id); // 递归构建子菜单
                    if (children.length > 0) {
                        return Object.assign({}, org, {
                            children: buildTree(list, org.id), // 递归构建子菜单
                        });
                    } else {
                        return Object.assign({}, org);
                    }
                });
        }
        // 构建树形结构
        const tree = buildTree(list, 'S1001');
        return tree;
    };
    const getdata = () => {
        request('/data/dynamic/query', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            data: {
                apiID: 'GZW_ORG_02'
            }
        }).then((res) => {
            const data = res?.data?.data;
            const tree = handleHblOrgTreeList(data);

            settreedata(tree);
        });
    };
    const handleObj = (obj, item) => {
        if (obj[item?.up_org_code]) {
            if (!obj[item?.up_org_code]['children']) {
                obj[item?.up_org_code]['children'] = {};
            }

            obj[item?.up_org_code]['children'][item?.org_code] = item;
        } else {
            for (let i in obj) {
                if (obj[i]['children']) {
                    obj[i]['children'] = handleObj(obj[i]['children'], item);
                }
            }
        }

        return obj;
    };
    const handleData = (obj) => {
        let arr = [];
        for (let i in obj) {
            let item = {
                title: obj[i]['org_name'],
                key: obj[i]['org_code_id'] + ''
            };
            if (obj[i]['children']) {
                item['children'] = handleData(obj[i]['children']);
            }

            arr.push(item);
        }
        return arr;
    };
    useEffect(() => {
        getdata()
    }, [])
    const onChange = (e) => {
        setsearchStr(e.target.value)
    }
    return (
        <Modal
            title={'选择'}
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
            centered
            width={1000}
            maskClosable={false}
            bodyStyle={{
                maxHeight: window.innerHeight - 150,
                overflowY: 'auto',
            }}
        >
            <Input.Search value={searchStr} style={{ marginBottom: 8 }} placeholder="搜索" onChange={onChange} />
            {
                treeData.length > 0 && <Tree
                    treeData={treeData}
                    defaultCheckedKeys={[value]}
                    selectedKeys={[value]}
                    style={{ maxHeight: window.innerHeight - 250, overflowY: 'auto' }}
                    defaultExpandAll
                    fieldNames={{ title: 'name', key: 'id' }}
                    onSelect={(selectedKeys, e) => {
                        setvalue(selectedKeys[0])
                        console.log(e);
                        setselectObj({
                            id: e.node.id,
                            name: e.node.name
                        })
                    }}
                    titleRender={(node) => {
                        const issh = searchStr == '' ? false : (node.name.indexOf(searchStr) !== -1);
                        return <div className={issh ? 'indexHblTreeNode' : ''}>{node.name}</div>
                    }}
                />
            }
        </Modal>
    );
};
const SelectCom = forwardRef(SelectComp);
export default SelectCom;
